import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2022-12-13
 * Time:20:27
 */
class TcpServer{
    private ServerSocket listenSocket;
    public TcpServer(int port) throws IOException {
        listenSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动！");
        ExecutorService service= Executors.newCachedThreadPool();
        while(true){
            //先连接
            Socket clinetSocket=listenSocket.accept();
            //处理连接
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clinetSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }

    private void processConnection(Socket clinetSocket) throws IOException {
        System.out.println("客户端上线 "+clinetSocket.getInetAddress().toString()+" "+clinetSocket.getPort());
        try (InputStream inputStream=clinetSocket.getInputStream();
             OutputStream outputStream=clinetSocket.getOutputStream()){
            while(true) {
                Scanner scanner=new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.println("客户端下线"+clinetSocket.getInetAddress().toString()+" "+clinetSocket.getPort());
                    break;
                }
                //读取请求
                String request=scanner.next();
                //计算响应
                String response=process(request);
                //响应返回客户端
                PrintWriter printWriter= new PrintWriter(outputStream);
                printWriter.println(response);
                //刷新缓冲区
                printWriter.flush();
                System.out.println(clinetSocket.getInetAddress().toString()+" "+clinetSocket.getPort()+" "+
                        request+" "+response);
            }
        }finally {
            clinetSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }
}
public class TcpServerTest {
    public static void main(String[] args) throws IOException {
        TcpServer tcpServer=new TcpServer(9090);
        tcpServer.start();
    }
}
